import os
import urllib.request


def format_progress_bar(downloaded, total_size, bar_length=50):
    percent = downloaded / total_size
    filled = int(bar_length * percent)
    bar = '#' * filled + ' ' * (bar_length - filled)
    progress = f"\r🔜 正在下载「 {bar} 」 {downloaded / 1024 / 1024:.1f}/{total_size / 1024 / 1024:.1f} M ¦ {percent * 100:.1f}%"
    print(progress, end='')


def download_any_file(url: str):
    default_url = 'https://github.com/amzxyz/rime_wanxiang_pro/releases/download/dict-nightly/9-cn_dicts.zip'
    url = url or default_url

    filename = os.path.basename(url)
    if not filename:
        filename = 'file.zip'

    try:
        with urllib.request.urlopen(url) as response:
            total_size = int(response.headers.get('content-length', 0))
            downloaded = 0
            chunk_size = 8192  # 8KB

            with open(filename, 'wb') as f:
                while True:
                    chunk = response.read(chunk_size)
                    if not chunk:
                        break
                    f.write(chunk)
                    downloaded += len(chunk)
                    format_progress_bar(downloaded, total_size)

        print("\n下载完成！")

    except Exception as e:
        print(f"\n下载失败：{e}")


if __name__ == '__main__':
    url = 'https://github.com/amzxyz/rime_wanxiang_pro/releases/download/dict-nightly/9-cn_dicts.zip'
    download_any_file(url)
